<!-- 申请发票 -->
<template>
    <page-header-wrapper @back="() => $router.go(-1)">
        <a-card :bordered="false" >
            <a-card :bordered="false" class="grey">
                <a-descriptions title="申请发票">
                    <a-descriptions-item :span="3">目前只支持纸质发票申请，暂不支持电子发票，申请发票前请先选择供应商，再选择开票内容</a-descriptions-item>
                </a-descriptions>
                <div class='table-page-search-wrapper'>
                    <a-form layout='inline'>
                        <a-row :gutter='48'>
                            <a-col :md='12' :sm='24'>
                                <a-form-item label="供应商">
                                    <a-select v-model="companyId" placeholder="请选择" @change="getData">
                                        <a-select-option v-for="item in companyList" :key="item.id" :value="item.id">{{item.companyName}}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :md='12' :sm='24'>
                                <a-form-item label="开票内容">
                                    <a-input v-model="receiptName" placeholder="请输入开票内容" allow-clear></a-input>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-card>
            <a-card :bordered="false">
                <div style="margin-bottom: 20px">可开票金额（¥）：</div>
                <a-row :gutter='48'>
                    <a-col :md='12' :sm='24'>
                        <span style="font-size: 16px;font-weight: 500;color: #333">{{canReceiptAmount}}</span>
                        <a-divider type="vertical" />
                        <a href="javascript:void(0)" @click="$router.push({path: '/companysInvoice/invoiceConfigs'})">发票抬头管理</a>
                        <a-divider type="vertical" />
                        <a href="javascript:void(0)" @click="$router.push({path: '/companysInvoice/invoiceAddress'})">发票收件地址管理</a>
                    </a-col>
                    <a-col :md='12' :sm='24'>
                        <a-row :gutter='48'>
                            <a-col :md='12' :sm='24'>
                                <a-range-picker @change="onDateChange" allow-clear/>
                            </a-col>
                            <a-col :md='12' :sm='24'>
                                <a-input-search v-model="query" placeholder="项目名称/结算单名称" @search="getData" allow-clear/>
                            </a-col>
                        </a-row>
                    </a-col>
                </a-row>

                <a-table style="margin-top: 20px" rowKey="id" :row-selection="{ selectedRowKeys: settlementIds, onChange: onSelectChange }" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ 'total': total ,'showSizeChanger': true,'pageSize': size,}" size="small" :scroll="{ x: 1200, }">
                    <div slot="operation" slot-scope="text,record">
                        <div>{{parseFloat(record.successAmount) + parseFloat(record.successServiceAmount)}}</div>
                    </div>
                </a-table>

                <div class="flex spaceBetween alignCenter" style="margin-top: 20px;">
                    <div>待开票金额（￥）：<span style="font-size: 16px;font-weight: 500;color: #333">{{amount}}</span></div>
                    <div class="flex alignCenter">
                        <a-button style="margin-right: 20px" type="" @click="() => $router.go(-1)">取消</a-button>
                        <a-button type="primary" @click="submit">提交</a-button>
                    </div>
                </div>
            </a-card>
        </a-card>

        <!-- 确认开票内容 -->
        <a-modal 
            v-model="visible" 
            width="60%"
            @ok="handleOk" 
            @cancel="visible = false">
            <div slot="title" style="text-align: center">确认开票内容</div>
            <div>
                <div v-if="companyId">供应商：{{companyList.find(item => item.id == companyId).companyName}}</div>
                <div style="margin: 12px 0">开票内容：{{receiptName}}</div>
                <div>
                    <a-row :gutter='48'>
                        <a-col :md='12' :sm='24'>
                            <div style="margin-bottom: 12px" class="flex alignCenter spaceBetween">
                                <div>发票信息</div>
                                <a href="javascript:void(0)" style="font-size: 12px" v-if="invoiceConfig.id" @click="$router.push({path: '/companysInvoice/invoiceConfigs'})">修改发票信息</a>
                            </div>
                            <a-card style="min-height: 200px">
                                <div v-if="!invoiceConfig || invoiceConfig.id == null || invoiceConfig.id == ''" class="flex flexCenter" style="height: 180px">
                                    <a href="javascript:void(0)" @click="$router.push({path: '/companysInvoice/invoiceConfigs'})">添加发票信息</a>
                                </div>
                                <div v-else class="applyDetail">
                                    <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" size="mini">
                                        <a-form-item label="发票抬头">
                                            <div>{{invoiceConfig.receiptTitle}}</div>
                                        </a-form-item>
                                        <a-form-item label="发票类型">
                                            <div>{{invoiceConfig.receiptType == '1' ? '增值税普通发票' : '增值税专用发票'}}</div>
                                        </a-form-item>
                                        <a-form-item label="纳税人识别号">
                                            <div>{{invoiceConfig.identificationNum}}</div>
                                        </a-form-item>
                                        <a-form-item label="基本开户银行">
                                            <div>{{invoiceConfig.channel}}</div>
                                        </a-form-item>
                                        <a-form-item label="基本开户账号">
                                            <div>{{invoiceConfig.bankAccount}}</div>
                                        </a-form-item>
                                        <a-form-item label="企业注册地址">
                                            <div>{{invoiceConfig.companyRegisterAddress}}</div>
                                        </a-form-item>
                                        <a-form-item label="税务登记固定电话">
                                            <div>{{invoiceConfig.taxRegisterTel}}</div>
                                        </a-form-item>
                                    </a-form>
                                </div>
                            </a-card>
                        </a-col>
                        <a-col :md='12' :sm='24'>
                            <div style="margin-bottom: 12px" class="flex alignCenter spaceBetween">
                                <div>收件地址</div>
                                <a href="javascript:void(0)" style="font-size: 12px" v-if="addressDefault.id" @click="selAddress">切换收件地址</a>
                            </div>
                            <a-card>
                                <div v-if="!addressDefault || addressDefault.id == null || addressDefault.id == ''" class="flex flexCenter">
                                    <a href="javascript:void(0)" @click="$router.push({path: '/companysInvoice/invoiceAddress'})">添加收件信息</a>
                                </div>
                                <div v-else class="applyDetail">
                                    <a-form :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }" size="mini">
                                        <a-form-item >
                                            <div>{{addressDefault.userName}} {{addressDefault.phone}}</div>
                                        </a-form-item>
                                        <a-form-item>
                                            <div>{{addressDefault.addressDetail}}</div>
                                        </a-form-item>
                                    </a-form>
                                </div>
                            </a-card>
                            <div style="margin: 12px 0">备注</div>
                            <a-textarea v-model="remark" placeholder="请输入备注信息，最多50字" :maxLength="50" :auto-size="{ minRows: 5, maxRows: 7 }" allowClear/>
                        </a-col>
                    </a-row>
                </div>
            </div>
        </a-modal>

        <!-- 切换收件地址 -->
        <a-modal 
            v-model="selAddressVisiible" 
            title="设置所属客户"
            @ok="selAddressHandleOk" 
            @cancel="selAddressVisiible = false">
            <div>
                <a-table rowKey="id" :row-selection="{ selectedRowKeys: setAddressId, onChange: onSelectAddressChange }" :columns="addressColumns" :data-source="addressList" size="small">
                </a-table>
            </div>
        </a-modal>
    </page-header-wrapper>
</template>

<script>
import { columns } from './table';
import { addressColumns } from './tableAddress';
import { getSettlementReceiptList , settlementCanReceiptAmount } from '@/api/companys/settlement';
import { queryMyCompany } from '@/api/services/company';
import { getReceiptAddressDefault , createReceipt , getReceiptConfig , getReceiptAddress } from '@/api/companys/invoice';
import { findItem } from '@/utils/util';
export default {
    name: 'companysInvoiceApply',
    data () {
        return {
            isload: false,
            dataList: [],
            page: 1,
            size: 10,
            total: 0,
            columns,
            startTime: '',
            endTime: '',
            companyId: undefined,
            query: '', // 项目名称/结算单名称
            receiptName: '', // 开票内容
            companyList: [], // 供应商列表
            amount: 0, // 待开票金额
            settlementIds: [], // 选择待开票结算信息ids
            addressDefault: {
                id: '',
                userName: '',
                phone: '',
            },
            invoiceConfig: {
                id: '',
                receiptTitle: '',
                receiptType: 1,
                identificationNum: '',
                channel: '',
                bankAccount: '',
                companyRegisterAddress: '',
                taxRegisterTel: '',
            },
            visible: false,
            remark: '', // 开票备注信息
            selAddressVisiible: false,
            addressList: [],
            setAddressId: [],
            addressColumns,
            canReceiptAmount: 0, // 可开票金额
        };
    },
    created(){
        this.getDefaultAddress();
        this.getInvoiceConfig();
        this.getCompany();
        this.getCanReceiptAmount();
    },
    activated(){
        this.getDefaultAddress();
        this.getInvoiceConfig();
    },
    beforeRouteLeave(to,from,next){
        this.visible = false;
        next();
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = `${dateStr[0]}`
                this.endTime = `${dateStr[1]}`
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取可开票结算列表数据
        getData(){
            let _this = this;
            _this.isload = true;
            const params = {
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'query': _this.query, 
                'companyId': _this.companyId,
                'pageSize': _this.size,
                'pageIndex': _this.page,
            }
            getSettlementReceiptList(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                    _this.amount = 0;
                    _this.settlementIds = [];
                    _this.getCanReceiptAmount();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 获取供应商列表
        getCompany(){
            let _this = this;
            return new Promise((resolve,reject) => {
                queryMyCompany()
                .then(res => {
                    if(res.success){
                        _this.companyList = res.data;
                        resolve();
                    }else{
                        _this.$notification['error']({
                            message: '温馨提示',
                            description: res.errMessage,
                            duration: 8
                        })
                        reject();
                    }
                })
            })
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            let _this = this
            let id = findItem(_this.settlementIds,selectedRowKeys);
            console.log(id,'ids')
            var rows = _this.dataList.find(item => item.id == id);
            if(_this.settlementIds.length < selectedRowKeys.length){
                this.amount += (parseFloat(rows.successAmount) + parseFloat(rows.successServiceAmount))
            }else{
                this.amount -= (parseFloat(rows.successAmount) + parseFloat(rows.successServiceAmount))
            }
            _this.settlementIds = selectedRowKeys;
        },
        // 获取默认发票收件地址
        getDefaultAddress(){
            let _this = this;
            return new Promise((resolve,reject) => {
                getReceiptAddressDefault().then(res => {
                    if(res.success){
                        _this.addressDefault = JSON.parse(JSON.stringify(res.data));
                        resolve();
                    }else{
                        _this.$notification['error']({
                            message: '温馨提示',
                            description: res.errMessage,
                            duration: 8
                        })
                        reject();
                    }
                })
            })
        },
        // 获取发票抬头
        getInvoiceConfig(){
            let _this = this;
            return new Promise((resolve,reject) => {
                getReceiptConfig().then(res => {
                    if(res.success){
                        _this.invoiceConfig = JSON.parse(JSON.stringify(res.data));
                        resolve();
                    }else{
                        _this.$notification['error']({
                            message: '温馨提示',
                            description: res.errMessage,
                            duration: 8
                        })
                        reject();
                    }
                })
            })
        },
        // 确认开票
        submit(){
            let _this = this;
            if(_this.companyId === undefined){
                _this.$message.warning('请选择供应商')
                return;
            }
            if(_this.receiptName === ''){
                _this.$message.warning('请输入开票内容')
                return;
            }
            if(_this.dataList.length == 0){
                _this.$message.warning('该供应商暂无可开票金额')
                return;
            }else if( _this.settlementIds.length == 0){
                _this.$message.warning('请选择待开票金额')
                return;
            }
            this.visible = true;
        },
        // 确认开票内容
        handleOk(){
            let _this = this;
            if(!_this.invoiceConfig.id){
                _this.$message.warning('请选择发票信息')
                return;
            }
            if(!_this.addressDefault.id){
                _this.$message.warning('请选择收件地址')
                return;
            }
            const params = {
                'receiptName': _this.receiptName,
                'companyId': _this.companyId,
                'receiptAddressId': _this.addressDefault.id,
                'remark': _this.remark,
                'settlementIds': _this.settlementIds,
            }
            createReceipt(params)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '发票已提交，请等待审核',
                        duration: 8
                    })
                    _this.$router.go(-1)
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 切换收件地址
        selAddress(){
            let _this = this;
            const params = {
                'pageSize': 99,
                'pageIndex': 1,
            }
            getReceiptAddress(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.addressList = res.data;
                    _this.selAddressVisiible = true;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        onSelectAddressChange(selectedRowKeys){
            if(this.setAddressId.length < selectedRowKeys.length){
                let id = findItem(this.setAddressId,selectedRowKeys);
                console.log(id,'id');
                this.setAddressId = id;
            }else{
                this.setAddressId = selectedRowKeys;
            }
        },
        selAddressHandleOk(){
            if(this.setAddressId.length > 0){
                this.addressDefault = this.addressList.find(item => item.id == this.setAddressId.join(','))
            }
            this.selAddressVisiible = false;
        },
        // 获取可开票金额
        getCanReceiptAmount(){
            let _this = this;
            const params = {
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'query': _this.query, 
                'companyId': _this.companyId,
                'pageSize': 99,
                'pageIndex': 0,
            }
            settlementCanReceiptAmount(params)
            .then(res => {
                if(res.success){
                    _this.canReceiptAmount = res.data
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
    }
}

</script>
<style scoped>
.grey{
    background: #EEE;
}
.applyDetail .ant-form-item{
    margin-bottom: 0;
}
</style>